import { expect } from '@jest/globals';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import { commonJson5Operation, initPreviewConfigFile, readJson5 } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import fse from "fs-extra";

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.StaticLibrary]
};

/**
 * 1、新建工程
 * 2、预览
 * 3、在页面最后添加#符号
 * 4、删除该符号
 * 预期结果：
 * 删除该符号后触发热加载生效
 * 实际结果：
 * 符合预期结果
 *
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const moduleRootPath = project.getModule('staticLibrary').moduleRootPath();
  await initPreviewConfigFile(moduleRootPath, 'staticLibrary', 'Hello');
  // eslint-disable-next-line max-len
  const commands: string[] = '--mode module -p module=staticLibrary@default -p product=default -p previewer.replace.page=Hello -p pageType=page -p compileResInc=true -p previewMode=true -p buildRoot=.preview PreviewBuild --watch --analyze=normal --parallel --incremental --daemon'.split(' ');
  const pkgName = '@test/library';
  await commonJson5Operation(path.resolve(moduleRootPath, 'oh-package.json5'), async (json) => {
    json.name = pkgName;
    return json;
  });
  const code = `
  @Preview
  @Component
  export struct Hello {
    build() {
      Text("fffff")
    }
  }
  `;
  fse.writeFileSync(`${moduleRootPath}/src/main/ets/Hello.ets`, code);
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('执行预览构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  const moduleJsonPath = path.join(moduleRootPath, '.preview', 'default', 'intermediates', 'res', 'default', 'module.json');
  const json = await readJson5(moduleJsonPath);
  expect(json.module.packageName === pkgName).toEqual(true);
  const loaderJsonPath = path.join(moduleRootPath, '.preview', 'default', 'intermediates', 'loader', 'default', 'loader.json');
  const loaderJson = await readJson5(loaderJsonPath);
  expect(loaderJson.byteCodeHar !== true).toEqual(true);
};

TestCaseBuilder.builder()
  .caseName('har-in-preview')
  // eslint-disable-next-line max-len
  .description('HAR模块在预览时，需要当做hap来处理，且res下的module.json需要插入packageName')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testfun)
  .load();
